import React, { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate, useOutletContext } from 'react-router-dom';
import { Card, Notebook } from '../../types';
import CardList from './CardList';
import CardEditor from './CardEditor';
import styles from './Notebook.module.css';
import { fetchCards, createCard, updateCard, deleteCard } from './cardApi';

const NotebookView: React.FC = () => {
  const { notebookId } = useParams();
  const { notebooks, setNotebooks } = useOutletContext<{ notebooks: Notebook[]; setNotebooks: React.Dispatch<React.SetStateAction<Notebook[]>> }>();
  const [cardCache, setCardCache] = useState<{ [key: string]: Card[] }>({});
  const [cards, setCards] = useState<Card[]>([]);
  const [selectedCard, setSelectedCard] = useState<Card | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 当notebookId变化时，重置selectedCard
  useEffect(() => {
    setSelectedCard(null);
  }, [notebookId]);

  // 获取当前笔记本的卡片，优先查缓存
  useEffect(() => {
    if (!notebookId) return;
    
    const loadCards = async () => {
      setLoading(true);
      try {
        const data = await fetchCards(notebookId);
        setCards(data);
        setCardCache(prev => ({ ...prev, [notebookId as string]: data }));
      } catch (error) {
        console.error('获取卡片失败', error);
      } finally {
        setLoading(false);
      }
    };
    
    if (cardCache[notebookId as string]) {
      // 使用缓存数据
      setCards(cardCache[notebookId as string]);
    } else {
      // 加载新数据
      loadCards();
    }
  }, [notebookId, cardCache]);

  // 获取当前笔记本信息
  const currentNotebook = useMemo(() => {
    return notebooks.find(notebook => notebook.id === notebookId);
  }, [notebookId, notebooks]);

  const filteredCards = useMemo(() => {
    return cards.filter(
      (card) =>
        card.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        card.content.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [cards, searchTerm]);

  // 修改后的创建卡片函数，不发送网络请求，直接创建临时卡片
  const handleCreateCard = () => {
    if (!notebookId) return;
    
    // 创建临时卡片对象，使用临时ID
    const tempId = `temp-${Date.now()}`;
    const tempCard: Card = {
      id: tempId,
      notebook_id: notebookId,
      title: '新建卡片',
      content: '',
      created_at: new Date(),
      next_review: new Date(Date.now() + 24 * 60 * 60 * 1000),
      ease_factor: 2.5,
      repetition: 0,
      interval: 0
    };
    
    // 更新本地状态，但不发送网络请求
    setCards(prev => [...prev, tempCard]);
    setSelectedCard(tempCard);
  };

  const handleSaveCard = async (updatedCard: Card) => {
    try {
      let savedCard: Card;
      
      // 检查是否为临时卡片（需要创建而不是更新）
      if (updatedCard.id.startsWith('temp-')) {
        // 这是一个新卡片，需要创建
        const { id, ...cardWithoutId } = updatedCard;
        savedCard = await createCard(cardWithoutId);
        
        // 从本地状态中移除临时卡片，添加新保存的卡片
        setCards(prev => {
          const newCards = prev.filter(card => card.id !== updatedCard.id);
          return [...newCards, savedCard];
        });
        
        // 更新缓存
        setCardCache(prev => {
          const currentNotebookCards = prev[notebookId as string] || [];
          const updatedCards = currentNotebookCards.filter(card => card.id !== updatedCard.id);
          return {
            ...prev,
            [notebookId as string]: [...updatedCards, savedCard]
          };
        });
      } else {
        // 这是现有卡片，需要更新
        savedCard = await updateCard(updatedCard);
        
        // 更新本地状态
        setCards(prev => prev.map(card => 
          card.id === updatedCard.id ? savedCard : card
        ));
        
        // 更新缓存
        setCardCache(prev => {
          const currentNotebookCards = prev[notebookId as string] || [];
          return {
            ...prev,
            [notebookId as string]: currentNotebookCards.map((card: Card) => 
              card.id === updatedCard.id ? savedCard : card
            )
          };
        });
      }
      
      // 更新选中的卡片
      setSelectedCard(savedCard);
      
      // 更新当前笔记本的cardCount
      if (updatedCard.id.startsWith('temp-')) {
        const updatedNotebooks = notebooks.map(nb => 
          nb.id === notebookId 
            ? { ...nb, cardCount: nb.card_count + 1 } 
            : nb
        );
        setNotebooks(updatedNotebooks);
      }
    } catch (e) {
      console.error('保存卡片失败', e);
    }
  };

  const handleDeleteCard = async (cardId: string) => {
    // 如果是临时卡片，直接从本地状态中删除
    if (cardId.startsWith('temp-')) {
      setCards(prev => prev.filter(card => card.id !== cardId));
      if (selectedCard?.id === cardId) setSelectedCard(null);
      return;
    }
    
    // 保存当前状态，以便在删除失败时恢复
    const previousCards = [...cards];
    const previousCardCache = { ...cardCache };
    const previousSelectedCard = selectedCard;
    
    // 乐观更新：立即从UI中删除卡片
    setCards(prev => prev.filter(card => card.id !== cardId));
    setCardCache(prev => {
      const updated = {
        ...prev,
        [notebookId as string]: (prev[notebookId as string] || []).filter((card: Card) => card.id !== cardId)
      };
      return updated;
    });
    
    // 更新当前笔记本的cardCount
    const updatedNotebooks = notebooks.map(nb => 
      nb.id === notebookId 
        ? { ...nb, cardCount: Math.max(0, nb.card_count - 1) } 
        : nb
    );
    setNotebooks(updatedNotebooks);
    
    // 如果当前选中的卡片被删除，清除选中状态
    if (selectedCard?.id === cardId) setSelectedCard(null);
    
    // 异步发送删除请求到后端
    try {
      await deleteCard(cardId);
      // 删除成功，不需要额外操作
    } catch (e) {
      console.error('删除卡片失败', e);
      
      // 删除失败，恢复之前的状态
      setCards(previousCards);
      setCardCache(previousCardCache);
      setSelectedCard(previousSelectedCard);
      
      // 恢复笔记本计数
      const restoredNotebooks = notebooks.map(nb => 
        nb.id === notebookId 
          ? { ...nb, cardCount: nb.card_count + 1 } 
          : nb
      );
      setNotebooks(restoredNotebooks);
      
      // 显示错误提示
      alert('删除卡片失败，请重试');
    }
  };

  if (!currentNotebook) {
    return <div className={styles.notebookView}>
      {loading ? '加载中...' : '您没有选择笔记本'}
    </div>;
  }

  return (
    <div className={styles.notebookView}>
      <div className={styles.notebookHeader}>
        <h2>{currentNotebook.name} <span className={styles.cardCount}>{filteredCards.length}张卡片</span></h2>
        <div className={styles.notebookActions}>
          <button className={styles.btnPrimary} onClick={handleCreateCard}>
            <i className="bi bi-plus-lg"></i> 新建卡片
          </button>
          <div className={styles.searchBox}>
            <i className="bi bi-search"></i>
            <input
              type="text"
              placeholder="搜索卡片..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
        </div>
      </div>

      <div className={styles.notebookContent}>
        <CardList
          cards={filteredCards}
          selectedCardId={selectedCard?.id}
          onSelectCard={setSelectedCard}
          onDeleteCard={handleDeleteCard}
        />
        {selectedCard && (
          <CardEditor
            key={selectedCard.id}
            card={selectedCard}
            onSave={handleSaveCard}
            onDeleteCard={handleDeleteCard}
          />
        )}
      </div>
    </div>
  );
};

export default NotebookView;  